package mysql

import (
	//"bluebell/models"
	"lottery/web/blue/bluebell/models"
	"strings"
)

// 创建帖子
func CreatePost(p *models.Post) (err error) {
	return db.Table("post").
		Select("post_id", "title", "content", "author_id", "community_id").
		Create(p).Error
}

// 获取帖子详情
func GetPostById(pid int64) (post *models.Post, err error) {
	// 这里还要初始化一下post，否则报错
	post = new(models.Post)
	err = db.Table("post").
		Where("post_id = ?", pid).
		Find(post).Error
	return
}

func Count() int64 {
	var num int64 = 0
	_ = db.Table("post").Where(&models.Post{}).Count(&num).Debug()
	return num
}

func CountC(pid int64) int64 {
	var num int64 = 0
	_ = db.Table("post").Where(&models.Post{CommunityID: pid}).Count(&num).Debug()
	return num
}

func GetPostList() (posts []*models.Post, err error) {
	posts = make([]*models.Post, 0, 2)
	err = db.Table("post").
		Find(&posts).Order("create_time desc").Limit(2).Error
	return
}

// 根据给定的id列表查询帖子数据
func GetPostListByIDs(ids []string) (postList []*models.Post, err error) {
	// 1. 获取相关帖子数据： 使用FIND_IN_SET(post_id, ?)函数，按照 IN 的顺序返回数据，有两种实现方式。
	postList = make([]*models.Post, 0, len(ids))
	err = db.Table("post").
		Select("post_id", "title", "content", "author_id", "community_id", "create_time").
		Where("post_id IN ? order by FIND_IN_SET(post_id, ?)", ids, strings.Join(ids, ",")).
		Find(&postList).Error
	if err != nil {
		return nil, err
	}
	return
}

func GetSomePost(com string) []*models.Post {
	postList := make([]*models.Post, 0)
	_ = db.Table("post").Where("title like ?", "%"+com+"%").Find(&postList).Error
	return postList
}
